package com.chinaunicom.emergency.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinaunicom.emergency.model.YjglUser;
import com.chinaunicom.emergency.repository.RolePermissionsRepository;
import com.chinaunicom.emergency.repository.UserRoleRepository;
import com.chinaunicom.emergency.repository.UsersRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Log4j2
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private RolePermissionsRepository rolePermissionsRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        YjglUser yjglUser = usersRepository.findByUserNameAndIsSoftDel(username,0);
        if(null == yjglUser){
            throw new OAuth2Exception("用户不存在!");
        }
        if (yjglUser.getAccountIsNotLocked() == 0) {
            throw new UsernameNotFoundException("输入的用户已锁定,请联系管理员");
        }

        log.info("oauth2登录用户：" + yjglUser.getUserName());
        List<String> roleIds = userRoleRepository.findRoleIdByUserId(yjglUser.getPid());
        JSONObject jsonObject = new JSONObject();
        if(!CollectionUtils.isEmpty(roleIds)){
            List<Object[]> permissions = rolePermissionsRepository.findPermissionByRoleId(roleIds);
            if (permissions != null) {
                for (int i = 0; i < permissions.size(); i++) {
                    Object[] objs = permissions.get(i);
                    JSONArray array = jsonObject.getJSONArray((String) objs[2]);
                    if (array != null) {
                        array.add(objs[0]);
                    } else {
                        JSONArray temp = new JSONArray();
                        temp.add(objs[0]);
                        jsonObject.put((String) objs[2], temp);
                    }
                }
            }
            log.info("权限列表为：" + jsonObject.toJSONString());
        }
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        grantedAuthorityList.add(new MyGrantedAuthority(jsonObject.toJSONString()));
        boolean enable = false;
        if(yjglUser.getEnabled() == 1){
            enable = true;
        }
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = false;
        if(yjglUser.getAccountIsNotLocked() == 1){
            accountNonLocked = true;
        }
        return new User(username, yjglUser.getPassword(),enable,accountNonExpired,credentialsNonExpired,accountNonLocked, grantedAuthorityList);
    }
}
